//
//  HOTStoreViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-4.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTStoreViewController.h"
#import "HOTStoreCell.h"
#import <StoreKit/StoreKit.h>
#import "NSData+Base64.h"



@interface HOTStoreViewController () <HOTStoreCellDelegate, UITableViewDataSource, UITableViewDelegate> {
    
    NSInteger _pageNo;
}
@property(nonatomic,strong)NSMutableArray *dataList;
@end

@implementation HOTStoreViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNaviTitle:@"売店"];
    
    //重新初始化hud 的parent view 设为window
    [self initHudWithView:[[UIApplication sharedApplication] keyWindow]];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_shop"]];

    
    _tableView.showFooter = NO;
    _tableView.showHeader = NO;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };
    
    self.dataList = [NSMutableArray array];
    
    _pageNo = 1;
    [self requestDataFromNet];
    
    //查询余额
    [self selectBalance];
}


-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_CLIENT_TYPE:kClientType,
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    [self requestWithURL:HOT_URL_PRODUCT_LIST Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

//查询余额
-(void)selectBalance {
    
    //[self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId};
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    [self requestWithURL:HOT_URL_FIND_BALANCE Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        [tempObj loadingSuccess];
        
        _balanceLabel.text = [HOTUtils getString:[data objectForKey:@"user_balance"]];
    
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}


-(void)createOrder:(SKProduct *)product {
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_PRODUCT_ID:product.productIdentifier,
                                 REQ_KEY_CLIENT_TYPE:kClientType};
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    [self requestWithURL:HOT_URL_ORDER_ADD Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        NSString *order = [data objectForKey:@"order_id"];
        
        [tempObj toPaymentWithProduct:product orderId:order];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)sendDataToVerify:(NSString *)rec orderId:(NSString *)orderId{
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_ORDER_ID:orderId,
                                 REQ_KEY_VERIFY_DATA:rec,
                                 REQ_KEY_CLIENT_TYPE:kClientType};
    
    [self showLoadingWithMessage:MSG_IS_VERIFY];
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    [self requestWithURL:HOT_URL_ORDER_VERIFY Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        
        [tempObj showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [self showLoading];
            [tempObj selectBalance];
        }];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)toPaymentWithProduct:(SKProduct *)product orderId:(NSString *)orderId{
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    [self.storeHandler addPayment:product.productIdentifier success:^(SKPaymentTransaction *transaction) {
        
        
        [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] keyWindow] animated:NO];
//        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
//                                                              message:@"支付成功"
//                                                             delegate:nil
//                                                    cancelButtonTitle:nil
//                                                     otherButtonTitle:ALERT_BTN_OK];
//        
//        [popupView showInWindow];
        
        NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        // 从沙盒中获取到购买凭据
        NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];

        [tempObj sendDataToVerify:[receiptData base64EncodedString] orderId:orderId];
        
    } failure:^(SKPaymentTransaction *transaction, NSError *error) {
        [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] keyWindow] animated:YES];
        
        
        if (error.code == RMStoreErrorCodeUnknownProductIdentifier) {

            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:@"未知的商品id"
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTStoreCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.delegate = self;
    cell.indexPath = indexPath;
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    cell.titleLabel.text = [dic objectForKey:@"product_name"];
    cell.priceLabel.text = [dic objectForKey:@"price"];
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 94;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    NSArray *purchasedProducts = [rmStore purchasedProductIdentifiers];
//    NSString *productID = [purchasedProducts objectAtIndex:indexPath.row];

    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma store cell delegate
-(void)toBuyBtnClickedByIndexPath:(NSIndexPath *)indexPath {
    
    __unsafe_unretained HOTStoreViewController *tempObj = self;
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    [self showLoading];
    
    [self.storeHandler requestProducts:[NSSet setWithObjects:[dic objectForKey:@"product_id"], nil] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        
        if (products.count > 0) {
            
            [tempObj createOrder:[products firstObject]];
            
        } else {
            
           [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] keyWindow] animated:YES];
        }
        
    } failure:^(NSError *error) {
        
        [tempObj loadingSuccess];
        if (error.code == RMStoreErrorCodeUnknownProductIdentifier) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:@"未知的商品id"
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
    
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
